package com.excesys.exsecs.access.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.excesys.exsecs.access.entity.AccessCategory;
import com.excesys.exsecs.access.entity.AccessDeviceInfo;
import com.excesys.exsecs.access.entity.AccessSupplier;
import com.excesys.exsecs.access.service.AccessCategoryService;
import com.excesys.exsecs.access.service.AccessDeviceInfoService;
import com.excesys.exsecs.access.service.AccessSupplierService;
import com.excesys.exsecs.access.vo.AccessDeviceInfoVO;
import com.excesys.exsecs.access.vo.AccessProductVO;
import com.excesys.exsecs.admin.api.entity.SysScheduleEntity;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.annotation.RequestExcel;
import com.excesys.exsecs.common.log.annotation.SysLog;
import com.excesys.exsecs.access.entity.AccessProduct;
import com.excesys.exsecs.access.service.AccessProductService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import com.excesys.exsecs.common.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 设备产品表
 *
 * @author lxc
 * @date 2024-05-06 17:44:19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/accessProduct" )
@Tag(description = "accessProduct" , name = "设备产品表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class AccessProductController {

    private final AccessProductService accessProductService;
    private final AccessCategoryService accessCategoryService;
	private final AccessDeviceInfoService accessDeviceInfoService;
    private final AccessSupplierService accessSupplierService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param accessProduct 设备产品表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('access_accessProduct_view')" )
    public R getAccessProductPage(@ParameterObject Page page, @ParameterObject AccessProduct accessProduct) {
		LambdaQueryWrapper<AccessProduct> wrapper = Wrappers.<AccessProduct>lambdaQuery()
				.eq(StrUtil.isNotBlank(accessProduct.getCategory()), AccessProduct::getCategory, accessProduct.getCategory())
				.like(StrUtil.isNotEmpty(accessProduct.getName()), AccessProduct::getName, accessProduct.getName())
				.eq(StrUtil.isNotEmpty(accessProduct.getIsPublish()), AccessProduct::getIsPublish, accessProduct.getIsPublish());
        Page<AccessProduct> page1 = accessProductService.page(page, wrapper);
        if (ObjectUtils.isNotEmpty(page1) && CollectionUtils.isNotEmpty(page1.getRecords())) {
            page1.getRecords().forEach(it ->{
                if (StringUtils.isNotBlank(it.getSupplierCode())){
                    AccessSupplier supplier = accessSupplierService.getOne(Wrappers.<AccessSupplier>lambdaQuery().eq(AccessSupplier::getSupplierCode, it.getSupplierCode()));
                    if (Objects.nonNull(supplier)){
                        it.setSupplierName(supplier.getSupplierName());
                    }
                }
                if (StringUtils.isNotBlank(it.getCategory())){
                    AccessCategory category = accessCategoryService.getOne(Wrappers.<AccessCategory>lambdaQuery().eq(AccessCategory::getIdentify, it.getCategory()));
                    if (Objects.nonNull(category)){
                        it.setCategoryName(category.getName());
                    }
                }
            });
        }
        return R.ok(page1);
    }

	/**
	 * 列表
	 * @param accessProduct 设备产品表
	 * @return
	 */
	@Operation(summary = "列表" , description = "列表" )
	@GetMapping("/list" )
	//@PreAuthorize("@pms.hasPermission('access_accessProduct_view')" )
	public R list(@ParameterObject AccessProduct accessProduct) {
		LambdaQueryWrapper<AccessProduct> wrapper = Wrappers.<AccessProduct>lambdaQuery()
				.eq(StrUtil.isNotBlank(accessProduct.getCategory()), AccessProduct::getCategory, accessProduct.getCategory())
				.like(StrUtil.isNotEmpty(accessProduct.getName()), AccessProduct::getName,
						accessProduct.getName());
		return R.ok(accessProductService.list(wrapper));
	}


    /**
     * 通过id查询设备产品表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('access_accessProduct_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(accessProductService.getById(id));
    }

    /**
     * 新增设备产品表
     * @param accessProduct 设备产品表
     * @return R
     */
    @Operation(summary = "新增设备产品表" , description = "新增设备产品表" )
    @SysLog("新增设备产品表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('access_accessProduct_add')" )
    public R save(@Validated @RequestBody AccessProduct accessProduct) {
		long count = accessProductService.count(Wrappers.<AccessProduct>lambdaQuery().eq(AccessProduct::getName, accessProduct.getName().trim()));
		if (count > 0){
			return R.failed("产品名称已存在");
		}
		accessProduct.setProductKey(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
		boolean bool = accessProductService.saveProduct(accessProduct);
		if (bool){
			return R.ok();
		} else{
			return R.failed("新增失败");
		}
    }

    /**
     * 修改设备产品表
     * @param accessProduct 设备产品表
     * @return R
     */
    @Operation(summary = "修改设备产品表" , description = "修改设备产品表" )
    @SysLog("修改设备产品表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('access_accessProduct_edit')" )
    public R updateById(@Validated @RequestBody AccessProduct accessProduct) {
        return R.ok(accessProductService.updateById(accessProduct));
    }

    /**
     * 通过id删除设备产品表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除设备产品表" , description = "通过id删除设备产品表" )
    @SysLog("通过id删除设备产品表" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('access_accessProduct_del')" )
    public R removeById(@RequestBody Long[] ids) {
		//如果绑定了设备，则不能删除
		List<AccessProduct> products = accessProductService.listByIds(CollUtil.toList(ids));
		List<String> keys = products.stream().map(AccessProduct::getProductKey).collect(Collectors.toList());
		long count = accessDeviceInfoService.count(Wrappers.<AccessDeviceInfo>lambdaQuery().in(AccessDeviceInfo::getProductKey, keys));
		if (count > 0 ){
			return R.failed("已选产品已绑定产品，无法删除，如需删除产品，则先解绑设备");
		}
        return R.ok(accessProductService.removeBatch(CollUtil.toList(ids)));
    }

    /**
     * 导入产品
     * @param excelVOList 产品列表
     * @param bindingResult 错误信息列表
     * @return R
     */
    @PostMapping("/import")
    //@PreAuthorize("@pms.hasPermission('access_accessDeviceInfo_export')")
    public R importProduct(@RequestExcel List<AccessProductVO> excelVOList, BindingResult bindingResult) {
        return accessProductService.importProduct(excelVOList, bindingResult);
    }


    /**
     * 导出excel 表格
     * @param accessProduct 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('access_accessProduct_export')" )
    public List<AccessProduct> export(AccessProduct accessProduct,Long[] ids) {
        return accessProductService.list(Wrappers.lambdaQuery(accessProduct).in(ArrayUtil.isNotEmpty(ids), AccessProduct::getId, ids));
    }
}